import { Component, OnInit, AfterViewInit, OnDestroy, ViewChild } from '@angular/core';
import { EChartOption, ECharts } from 'echarts-ng2';
import { DateOptionService } from '../../../share/date-option.service';
import { DeviceService } from '../../../share/device.service';
import { Device, Select,
   ChartsQueryCondition, ChartOption, ChartsQueryConditionStr, FormatDate } from '../../../classes/Device';
import { Subscription } from 'rxjs/Rx';
import 'echarts/theme/macarons';
import { Http, Jsonp } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { EmitData } from 'app/time-type/time-type.component';
import { environment } from 'environments/environment';

@Component({
  selector: 'app-energy-query',
  templateUrl: './energy-query.component.html',
  styleUrls: ['./energy-query.component.css']
})
export class EnergyQueryComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChild('echarts') echarts: ECharts;
    public ths: Array<string> = ['名称', '日期', '日电量(kWh)']
    public trs: EnergyBackData;
    public selects: Array<Select>;
    public observable: Observable<any>;
    option: EChartOption;
    begindate: object;
    enddate: object;
    // 所观察的设备信息
    public deviceInfo: Device;
    _params: ChartsQueryConditionStr;

    // url = '/DSMService/GetCurver';
    url = environment.httpUrl;

  public datepickerOpts: object;

  public subscription: Subscription;
  constructor(
    public deviceService: DeviceService,
    public http: Http,
    public jsonp: Jsonp
  ) {
  }

  ngOnInit() {

    // 该组件初始化设备信息
    this.deviceInfo = this.deviceService.getDeviceInfo();

    // 初始化数据类型
    this.selects = [
        new Select('复费率电量', '1012'),
        new Select('电量', '1013')
      ];

    // 初始化时间
    const date = new Date();
    this.enddate = {
      formatted: new FormatDate(date).formatToString()
    }
    this.begindate = {
      formatted: new FormatDate(date).formatToString(10)
    }
    // 初始化查询参数
    this._params =  new ChartsQueryConditionStr(
        this.deviceInfo.meterID,
        '1012',
        this.begindate['formatted'],
        this.enddate['formatted'],
        'day',
    )

    this.observable = this.http.get(this.url, { params: this._params }).map( res => JSON.parse(res.json()) );
    this.observable.subscribe(
      (data: any) => {
        // console.log(JSON.parse(data))
        this.trs = data.data.detail;
        const chartOption = new ComplexEnergyChartOption(
            data.data
        );
        this.echarts.setOption(chartOption.getOption());
      },
      err => console.log(err)
    );
/*     this.trs = [
      {
        name: '电容器',
        date: '2017-05-03',
        energy: '1400'
      },
      {
        name: '电容器',
        date: '2017-05-03',
        energy: '1400'
      },
    ]; */
  }
  getDate(e: EmitData) {
    this._params.datetype = e.datetype;
    if (e.type === 'start') {
      this._params.begindate = e.event.formatted;
    } else {
      this._params.enddate = e.event.formatted;
    }
  }

  condition() {
    this.echarts.clear();

    this.observable = this.http.get(this.url, { params: this._params }).map( res => JSON.parse(res.json()) );

    this.observable.subscribe(
      (data: any) => {
        const chartOption = new ComplexEnergyChartOption(
          data.data,
          this._params.datatype
        );
        this.echarts.setOption( chartOption.getOption());

        if (data.data.detail !== undefined) {
          this.trs = data.data.detail;
        } else {
          this.trs = data.data;
        }
      },
      err => {
        console.log(err);
        alert('后台没有返回数据');
      }
    );
  }
    // 初始化完组件视图及其子视图之后启动订阅
    ngAfterViewInit(): void {
      this.subscription = this.deviceService.getMessage().subscribe(msg => {
        this.deviceInfo = msg;
        this._params.meterID = this.deviceInfo.meterID;
        this.observable = this.http.get(this.url, { params: this._params }).map( res => res.json() );
        this.observable.subscribe(
          data => {
            // console.log(JSON.parse(data))
            const chartOption = new ChartOption(
                JSON.parse(data),
                this._params.datatype
            );
            this.option = chartOption.getOption();
          },
          err => console.log(err)
        );
      })
    }

    // 组件销毁之前销毁取消订阅
    ngOnDestroy(): void {
        this.subscription.unsubscribe();
    }
}

export class ComplexEnergyBackData {
  jian: Array<number>;
  feng: Array<number>;
  ping: Array<number>;
  gu: Array<number>;
  date: Array<string>;
  detail: EnergyBackData;
}

export class EnergyBackData {
  Name: string;
  Date: string;
  Energy: number;
}

export class ComplexEnergyChartOption {
  constructor (
    public data: any,
    public datatype = '1012'
  ) {
  }
  getOption() {
    let option: EChartOption;
    if (this.datatype === '1012') {
      option = {
        tooltip : {
          trigger: 'axis',
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
              type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['尖', '峰', '平', '谷']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis:  {
          splitLine: {show: false},
          type : 'category',
          data : this.data.date,
          axisTick: {
              alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '尖',
            type: 'bar',
            stack: '总量',
            label: {
                normal: {
                    show: true,
                    position: 'insideRight'
                }
            },
            data: this.data.jian
          },
          {
            name: '峰',
            type: 'bar',
            stack: '总量',
            label: {
                normal: {
                    show: true,
                    position: 'insideRight'
                }
            },
            data: this.data.feng
          },
          {
            name: '平',
            type: 'bar',
            stack: '总量',
            label: {
                normal: {
                    show: true,
                    position: 'insideRight'
                }
            },
            data: this.data.ping
          },
          {
            name: '谷',
            type: 'bar',
            stack: '总量',
            label: {
                normal: {
                    show: true,
                    position: 'insideRight'
                }
            },
            data: this.data.gu
          }
        ]
      }
    } else {
      const chartData = {
        yData: new Array,
        xData: new Array
      }
      this.data.forEach(e => {
        chartData.yData.push(e.energy);
        chartData.xData.push(e.date);
      });
      console.log(chartData)
      option = {
        tooltip : {
          trigger: 'axis',
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
              type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['电量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis:  {
          splitLine: {show: false},
          type : 'category',
          data : chartData.xData,
          axisTick: {
              alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '电量',
            type: 'bar',
            stack: '总量',
            label: {
                normal: {
                    show: true,
                    position: 'insideRight'
                }
            },
            data: chartData.yData
          }
        ]
      }
    }
  return option;
  }
}
